<?php namespace App\Libs\Commons;
/**
 * @author	zhe.wang
 * @desc	日志调用
 */
use Illuminate\Support\Facades\Log;
class MyLogger {
	const DEBUG = 'debug';
	const INFO = 'info';
	const NOTICE = 'notice';
	const WARNING = 'warning';
	const ERROR = 'error';
	const CRITICAL = 'critical';
	const ALERT = 'alert';
	const EMERGENCY = 'emergency';
	
	static private $levels = [
		self::DEBUG		=> 100,
		self::INFO		=> 200,
		self::NOTICE		=> 300,
		self::WARNING	=> 400,
		self::ERROR		=> 500,
		self::CRITICAL	=> 600,
		self::ALERT		=> 700,
		self::EMERGENCY	=> 800
	];
	static private function parseLevel($level){
		return self::$levels[$level] ?? self::$levels[self::DEBUG];
	}
	
	static private function merge(array $context=array()){
		if(empty($_SERVER['unique_id'])){
			$_SERVER['unique_id'] = request('unique_id') ?? strtoupper(My_unique_code());
			$_SERVER['log_reference'] = 1;
			$_SERVER['REQUEST_URI'] = $_SERVER['REQUEST_URI'] ?? '';
		}
		list($t2, $t1) = explode(' ', microtime());
		return [
			'system'		=> [
				'unique_id'		=> $_SERVER['unique_id'],
				'microtime'		=> $t1 .'.'.ltrim($t2, '0.'),
				'log_reference' => $_SERVER['log_reference']++,
				'request_uri' 	=> $_SERVER['REQUEST_URI']
			],
			'context'	=> $context
		];
	}
	/**
	 * Log a message to the logs.
	 *
	 * @param  string  $level
	 * @param  string  $message
	 * @param  array  $context
	 * @return void
	 */
	static public function log($level, $message, array $context = array()) {
		$envLogLevel = strtolower(env('LOG_LEVEL'));
		if($envLogLevel){
			if(self::parseLevel($level) >= self::parseLevel($envLogLevel)){
				Log::$level($message, self::merge($context));
			}
		}
		return true;
	}
	static public function __callstatic($method, $params){
		self::log($method, $params[0], $params[1] ?? []);
	}
}